//
//  JMMiddleViewController.m
//  分页控制器
//
//  Created by JackMeng on 16/3/18.
//  Copyright © 2016年 JackMeng. All rights reserved.
//

#import "JMMiddleViewController.h"
#import "ProvinceDetailController.h"


@interface JMMiddleViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UITableView *tableVIew;

@property (nonatomic,strong) UIView *View1;

@property (nonatomic,assign) NSInteger currentPage;

//点击按钮 弹出的view
@property (nonatomic,strong) UIView *middleView;

//记录点击的按钮
@property (nonatomic,strong) UIButton *lastBtn;

//记录按钮点击的次数
@property (nonatomic,assign) NSInteger btnClick;

@end

@implementation JMMiddleViewController

static NSString *const ID = @"Cell";

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *view1 = [[UIView alloc] init];
    
    self.View1 = view1;
    
    [self.view addSubview:view1];
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top);
        
        make.left.equalTo(self.view.mas_left);
        
        make.right.equalTo(self.view.mas_right);
        
        make.height.equalTo(@150);
    }];
    
    
    UITableView *tab = [[UITableView alloc] init];
    
    self.tableVIew = tab;
    
    tab.delegate = self;
    
    tab.dataSource = self;
    
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(view1.mas_bottom);
        
        make.left.equalTo(self.view.mas_left);
        
        make.right.equalTo(self.view.mas_right);
        
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    [self setUp];
    
    __weak typeof (self) weakSelf = self;
    
    [self.tableVIew addHeaderWithCallback:^{
        
        [weakSelf loadData]; //加载网络数据
        
        
    }];
    [self.tableVIew headerBeginRefreshing];
    
    [self.tableVIew addFooterWithCallback:^{
       
        [weakSelf loadMore];
        
    }];

}

- (void)loadData{
    
    self.currentPage = 1;
    
    //省本级会员
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * pwdId = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * userHumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"userHumber"];
    
    NSString *json = [NSString stringWithFormat:@"{'action': getZLibrariesHygl,'service': MemberService, 'userName':'%@','password':'%@', 'vaueJson':'{userid :%@,pageNum:%ld,chapter:宁波}'}",userId,pwdId,userHumber,self.currentPage];
    
    NSArray * array = @[@{@"arg0":json}];
    [HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
        
        NSArray *arr = JSON[@"msg"];
        
        for (NSDictionary *dic in arr) {
            
            NSDictionary *dict = dic[@"attrs"];
            
            leftModel *leftM = [leftModel mj_objectWithKeyValues:dict];
            
            [self.dataArray addObject:leftM];
            
        }
        
        [self.tableVIew headerEndRefreshing];
        
        [self.tableVIew reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

- (void)loadMore{

    self.currentPage ++;
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * pwdId = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * userHumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"userHumber"];
    
    NSString *json = [NSString stringWithFormat:@"{'action': getJCLibrariesHygl,'service': MemberService, 'userName':'%@','password':'%@', 'vaueJson':'{userid :%@,pageNum:%ld,chapter:宁波}'}",userId,pwdId,userHumber,self.currentPage];
    
    NSArray * array = @[@{@"arg0":json}];
    [HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
        
        NSArray *arr = JSON[@"msg"];
        
        for (NSDictionary *dic in arr) {
            
            NSDictionary *dict = dic[@"attrs"];
            
            leftModel *leftM = [leftModel mj_objectWithKeyValues:dict];
            
            [self.dataArray addObject:leftM];
            
        }
        if (self.dataArray.count == 0) {
            
            [self.view makeToast:@"没有最新数据哦"];
        }
        
        [self.tableVIew footerEndRefreshing];
        
        [self.tableVIew reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)setUp{
    
    CGFloat W = (self.view.width - 50) / 4;
    
    CGFloat H = 30;
    
    NSArray *arr = @[@"宁波",@"温州",@"绍兴",@"湖州",@"嘉兴",@"金华",@"衢州",@"舟山",@"台州",@"丽水"];
    
    for (int i = 0 ; i < arr.count; i ++) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        btn.layer.cornerRadius = 15;
        [btn.layer setBorderColor:[UIColor orangeColor].CGColor];
        [btn.layer setBorderWidth:1];
        btn.layer.masksToBounds = YES;
        
        btn.tag = i + 1;
        
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        btn.titleLabel.font = [UIFont systemFontOfSize:12];
        
        btn.backgroundColor = [UIColor whiteColor];
        
        
        if (i >= 0 && i < 4) {
            btn.frame = CGRectMake(10 *(i + 1) + W*i, 15, W, H);

        }else if (i > 3 && i < 8) {
            
            btn.frame = CGRectMake(10 *(i -3) + W*(i-4), 60, W, H);
            
        }else{
            
            btn.frame = CGRectMake(10 *(i -7) + W*(i-8), 105, W, H);
            
        }
        
        [self.View1 addSubview:btn];
        
    }
    
}

//按钮点击---弹出一个框
- (void)btnClick:(UIButton *)btn{

    btn.backgroundColor = [UIColor orangeColor];
    [btn.titleLabel setTextColor:[UIColor whiteColor]];
//记录按钮点击次数
    if (self.lastBtn == btn) {
        btn.backgroundColor = [UIColor orangeColor];
        [btn.titleLabel setTextColor:[UIColor whiteColor]];

        self.btnClick ++;
        
    }else {
        
        [self.lastBtn setBackgroundColor:[UIColor whiteColor]];
        [self.lastBtn.titleLabel setTextColor:[UIColor blackColor]];
        self.tableVIew.hidden = NO;
        
        [self.middleView removeFromSuperview];
        
        self.btnClick = 0;
    }
    
//点击同一个按钮  移除middleView
    if (self.lastBtn == btn && (self.btnClick % 2 != 0)) {
        
        self.tableVIew.hidden = NO;
        
        [self.middleView removeFromSuperview];
        
        return;
        
    }
    
    NSArray *arr1 = @[@"海曙区",@"江东",@"江北",@"北仑",@"镇海",@"鄞州",@"慈溪",@"余姚",@"奉化",@"宁海",@"象山"];
    
    NSArray *arr2 = @[@"鹿城",@"瓯海",@"龙湾",@"乐清",@"瑞安",@"永嘉",@"洞头",@"平阳",@"泰顺",@"苍南",@"文成"];
    
    NSArray *arr3 = @[@"越城",@"柯桥",@"上虞",@"诸暨",@"嵊州",@"新昌"];
    
    NSArray *arr4 = @[@"吴兴",@"南浔",@"德清",@"安吉",@"长兴"];
    
    NSArray *arr5 = @[@"南湖",@"秀洲",@"平湖",@"海宁",@"桐乡",@"嘉善",@"海盐"];
    
    NSArray *arr6 = @[@"婺城",@"金东",@"兰溪",@"东阳",@"义务",@"永康",@"浦江",@"武义",@"磐安"];

    NSArray *arr7 = @[@"柯城",@"衢江",@"江北",@"龙游",@"常山",@"开化"];
    
    NSArray *arr8 = @[@"定海",@"普陀",@"岱山",@"嵊泗"];
    
    NSArray *arr9 = @[@"椒江",@"黄岩",@"路桥",@"温岭",@"临海",@"玉环",@"三门",@"天台",@"仙居"];
    
    NSArray *arr10 = @[@"莲都",@"龙泉",@"青田",@"云和",@"庆元",@"缙云",@"遂昌",@"松阳",@"景宁"];
    
    self.tableVIew.hidden = YES;
    
    UIView *middleView = [[UIView alloc] init];

    self.middleView = middleView;
    
    middleView.backgroundColor = [UIColor colorWithRed:236/255.0 green:247/255.0 blue:250/255.0 alpha:1];
    
    [self.view addSubview:middleView];
    
    [middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.View1.mas_bottom);
        
        make.left.equalTo(self.view.mas_left);
        
        make.right.equalTo(self.view.mas_right);
        
        make.height.equalTo(@100);
    }];
    
    self.lastBtn = btn;
    
    if (btn.tag == 1) {
        [self setButtonCount:arr1];
    }else if(btn.tag == 2){
        [self setButtonCount:arr2];

    
    }else if(btn.tag == 3){
        [self setButtonCount:arr3];

        
    }else if(btn.tag == 4){
        [self setButtonCount:arr4];

        
    }else if(btn.tag == 5){
        [self setButtonCount:arr5];

        
    }else if(btn.tag == 6){
        [self setButtonCount:arr6];

        
    }else if(btn.tag == 7){
        [self setButtonCount:arr7];

        
    }else if(btn.tag == 8){
        
        [self setButtonCount:arr8];

    }else if(btn.tag == 9){
        [self setButtonCount:arr9];

        
    }else if(btn.tag == 10){
        
        [self setButtonCount:arr10];

    }
    
}

//设置页面按钮个数
- (void)setButtonCount:(NSArray *)arr{
    
    CGFloat ViewW = self.view.frame.size.width;
    CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
    CGFloat h = 5;//用来控制button距离父视图的高
    for (int i = 0; i < arr.count; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//设置边框
        btn.layer.cornerRadius = 10;
        [btn.layer setBorderColor:[UIColor orangeColor].CGColor];
        [btn.layer setBorderWidth:1];
        btn.layer.masksToBounds = YES;
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        
//添加行为
        [btn addTarget:self action:@selector(middBtn:) forControlEvents:UIControlEventTouchUpInside];
        //计算大小
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10]};
        CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(ViewW, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
        
        btn.frame = CGRectMake(10 + w, h, length + 40 , 20);
        //当button的位置超出屏幕边缘时换行 320 只是button所在父视图的宽度
        if(10 + w + length + 40 > ViewW){
            w = 0; //换行时将w置为0
            h = h + btn.frame.size.height + 10;//距离父视图也变化
            btn.frame = CGRectMake(10 + w, h, length + 40, 20);//重设button的frame
            
        }
        w = btn.frame.size.width + btn.frame.origin.x;

        [self.middleView addSubview:btn];
        
    }

}

//点击按钮  列表数据改变
- (void)middBtn:(UIButton *)btn{

    [self.dataArray removeAllObjects];
    
    self.tableVIew.hidden = NO;
    
    [self.middleView removeFromSuperview];
    
    self.currentPage ++;
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSString * pwdId = [[NSUserDefaults standardUserDefaults]objectForKey:@"pwdId"];
    NSString * userHumber = [[NSUserDefaults standardUserDefaults]objectForKey:@"userHumber"];
    
    NSString *json = [NSString stringWithFormat:@"{'action': getJCLibrariesHygl,'service': MemberService, 'userName':'%@','password':'%@', 'vaueJson':'{userid :%@,pageNum:%ld,chapter:%@}'}",userId,pwdId,userHumber,self.currentPage,btn.titleLabel.text];
    
    NSArray * array = @[@{@"arg0":json}];
    [HttpTools requestWithURL:BaseURL arrays:array method:Basemethod success:^(id JSON) {
        
        NSArray *arr = JSON[@"msg"];
        
        for (NSDictionary *dic in arr) {
            
            NSDictionary *dict = dic[@"attrs"];
            
            leftModel *leftM = [leftModel mj_objectWithKeyValues:dict];
            
            [self.dataArray addObject:leftM];
            
        }
        if (self.dataArray.count == 0) {
            
            [self.view makeToast:@"没有最新数据哦"];
        }
        
//        [self.tableVIew footerEndRefreshing];
        
        [self.tableVIew reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    


}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.dataArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    leftModel *model = self.dataArray[indexPath.row];
    
    leftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        
        cell = [leftTableViewCell WithLeftTableViewCell];
        
    }
    
    cell.model = model;
    
    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    leftModel *model = self.dataArray[indexPath.row];
    
    ProvinceDetailController *proVC = [[ProvinceDetailController alloc] init];
    
    proVC.contId = model.ID;
    
    [self.navigationController pushViewController:proVC animated:YES];
    
}

@end







